﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AteneoLibriBusinessLogic.Entities;
using AteneoLibriBusinessLogic.Utility;

namespace AteneoLibriBusinessLogic.DAL
{
    public class SearchFacade
    {

        AteneoLibriEntityFramework.AteneoLibriEntities db = new AteneoLibriEntityFramework.AteneoLibriEntities();
        BookFacade bookFacade = new BookFacade();
        List<BookResults> searchResults = new List<BookResults>();

        public List<Book> Search(string query)
        {
            List<Book> books = bookFacade.getBooks();

            foreach (var entry in books)
            {
                string title = entry.Title.ToLower();
                string author = entry.Author.ToLower();

                double percentage1 = DistanceUtility.GetPercentage(DistanceUtility.CalculateRank(title, query, true), DistanceUtility.CalculateRank(title, title, false)); // GetPerfectMatch(entry.Title)
                double percentage2 = DistanceUtility.GetPercentage(DistanceUtility.CalculateRank(author, query, true), DistanceUtility.CalculateRank(author, author, false));
                double percentage3 = ((percentage1 * DistanceUtility.TITLE_WEIGHT) + (percentage2 * DistanceUtility.AUTHOR_WEIGHT)) / (DistanceUtility.TITLE_WEIGHT + DistanceUtility.AUTHOR_WEIGHT);
                if (percentage1 > DistanceUtility.THRESHOLD || percentage2 > DistanceUtility.THRESHOLD || percentage3 > DistanceUtility.THRESHOLD)
                {
                    BookResults bookResult = new BookResults(Math.Max(percentage1, Math.Max(percentage2, percentage3)), entry);

                    searchResults.Add(bookResult);
                }
            }

            searchResults = searchResults.OrderByDescending(x => x.Rank).ToList();

            return searchResults.Select(x => x.Book).ToList<Book>();
        }


        public List<Book> SearchNET(string query)
        {
            return null;
        }

    }
}
